<template>
	<div>
		<div style="position: fixed;z-index: 10;flex-direction: column;background: white;width: 100%;margin-top: -10px"><h1
				class="header-text">
			部门成员信息管理
		</h1>
			<div class="search-bar">
				<el-input placeholder="输入部门编号/部门名称/部门负责人  搜索部门" v-model="searchQuery" @input="handleInput">
				</el-input>
			</div>
			<div style="float:left;">
				<el-button type="primary" @click="handleAdd">新增用户
					<el-icon style="margin-left: 10px;">
						<CirclePlusFilled/>
					</el-icon>
				</el-button>
				<el-button type="danger" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除
					<el-icon style="margin-left: 10px;">
						<RemoveFilled/>
					</el-icon>
				</el-button>
			</div>
			<div style="float: right;margin-right: 100px">
				<el-pagination @size-change="handleSizeChange"
											 @current-change="handleCurrentChange"
											 :current-page="currentPage"
											 :page-sizes="[10, 20, 50,100]"
											 :page-size="pageSize"
											 layout="total, sizes, prev, pager, next, jumper"
											 :total="totalCount"
				/>
			</div>
		</div>
		<div class="table-container">
			<el-table
					:data="paginatedDepartments"
					style="width: 100%;top:160px;"
					@selection-change="handleSelectionChange"
					@row-click="handleRowClick"
			>
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column prop="did" label="部门编号" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.did)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="dname" label="部门名称" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.dname)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="dmanager" label="部门负责人" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.dmanager)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="dpassword" label="密码" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.dpassword)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="dphone" label="联系电话" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.dphone)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="text1" label="问题" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.problem)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="text2" label="答案" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.text)"></span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button type="danger" size="small" @click.stop="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!-- Modal dialog for department details -->
		<el-dialog v-model="dialogVisible" title="部门信息" @close="dialogVisible = false">
			<el-form :model="selectedDepartment" :rules="rules" ref="departmentForm">
				<el-form-item label="部门编号" prop="did">
					<el-input v-model="selectedDepartment.did" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门名称">
					<el-input v-model="selectedDepartment.dname" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="登录密码">
					<el-input v-model="selectedDepartment.dpassword" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门负责人">
					<el-input v-model="selectedDepartment.dmanager" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="联系电话">
					<el-input v-model="selectedDepartment.dphone" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="问题">
					<el-input v-model="selectedDepartment.problem" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="答案">
					<el-input v-model="selectedDepartment.text" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleConfirm" v-if="!isEdit">确认添加</el-button>
				<el-button type="primary" @click="handleConfirm" v-else>确认修改</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import AxiosService from '@/plugins/Axios.js';
import {ElMessage} from "element-plus";
import {CirclePlusFilled, RemoveFilled} from "@element-plus/icons-vue";

export default {
	components: {
		CirclePlusFilled,
		RemoveFilled
	},
	data() {
		return {
			searchQuery: '',
			paginatedDepartments: [],
			departments: [],
			selectedDepartment: {
				did: '',
				dname: '',
				dpassword: '',
				dmanager: '',
				dphone: '',
				problem: '',
				text: ''
			},
			rules: {
				did: [{
					required: true,
					message: '部门编号不能为空',
					trigger: 'blur'
				}],
			},
			dialogVisible: false,
			multipleSelection: [],
			didExistError: false,
			isEdit: false,
			originalDid: '',
			currentPage: 1,
			pageSize: 10,
			totalCount: 0,
			size: 'large',
			background: false,
			disabled: false
		};
	},
	computed: {
		paginatedDepartments() {
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;
			return this.paginatedDepartments.slice(start, end);
		}
	},
	methods: {
		handleInput() {
			// Perform exact matching search
			const results = this.departments.filter(department => {
				const searchString = `${department.did} ${department.dname} ${department.dmanager}`
				return searchString.includes(this.searchQuery);
			});
			// Assuming you want to sort by the length of matching characters
			results.sort((a, b) => {
				const aMatchLength = this.calculateMatchLength(a);
				const bMatchLength = this.calculateMatchLength(b);
				return bMatchLength - aMatchLength;
			});
			this.paginatedDepartments = results;
		},

		calculateMatchLength(department) {
			const searchString = `${department.did} ${department.dname} ${department.dmanager}`
			const matchIndex = searchString.indexOf(this.searchQuery);
			if (matchIndex !== -1) {
				return this.searchQuery.length;
			}
			return 0;
		},
		escapeRegExp(string) {
			return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
		},
		highlightMatch(text) {
			if (typeof text !== 'string') {
				text = String(text); // Convert non-string values to strings
			}
			if (!this.searchQuery) return text;
			const regex = new RegExp(this.escapeRegExp(this.searchQuery), 'gi');
			return text.replace(regex, (match) => `<span style="color: #ff00f3; font-weight: bolder">${match}</span>`);
		},


		async fetchDepartments() {
			try {
				const response = await AxiosService.fetchDepartments();
				this.departments = response;
				this.paginatedDepartments = response;
				this.totalCount = response.length;
			} catch (error) {
				ElMessage.error("获取部门列表失败")
			}
		},
		handleSizeChange(val) {
			this.pageSize = val;
		},
		handleCurrentChange(val) {
			this.currentPage = val;
		},
		handleAdd() {
			this.isEdit = false;
			this.resetForm();
			this.dialogVisible = true;
		},
		handleConfirm() {
			if (this.isEdit) {
				this.updateDepartment();
			} else {
				this.addDepartment();
			}
		},
		addDepartment() {
			AxiosService.addDepartment(this.selectedDepartment)
					.then(() => {
						this.dialogVisible = false;
						ElMessage.success('部门添加成功！');
						this.fetchDepartments()
					})
					.catch(error => {
						console.error('Error adding department: ', error);
						ElMessage.error('部门添加失败！');
					});
		},
		async handleBatchDelete() {
			try {
				const deletePromises = this.multipleSelection.map(department => AxiosService.deleteDepartment(department.did));
				await Promise.all(deletePromises);
				this.departments = this.departments.filter(department => !this.multipleSelection.includes(department));
				this.totalCount -= this.multipleSelection.length; // 更新总条数
				this.multipleSelection = []; // 清空选中
				this.$message({
					type: 'success',
					message: '批量删除成功!'
				});
				await this.fetchDepartments()
			} catch (error) {
				console.error('Error batch deleting students:', error);
				this.$message({
					type: 'error',
					message: '批量删除失败，请重试!'
				});
			}
		},
		updateDepartment() {
			AxiosService.updateDepartment(this.selectedDepartment)
					.then(() => {
						const index = this.departments.findIndex(d => d.did === this.originalDid);
						if (index !== -1) {
							this.departments.splice(index, 1, this.selectedDepartment);
						}
						this.dialogVisible = false;
						ElMessage.success('部门更新成功！');
						this.fetchDepartments()
					})
					.catch(error => {
						console.error('Error updating department: ', error);
						ElMessage.error('部门更新失败！');
					});
		},
		handleDelete(index, row) {
			AxiosService.deleteDepartment(row.did)
					.then(() => {
						this.departments.splice(index, 1);
						this.totalCount--;
						ElMessage.success('部门删除成功！');
						this.fetchDepartments()
					})
					.catch(error => {
						console.error('Error deleting department: ', error);
						ElMessage.error('部门删除失败！');
					});
		},
		handleRowClick(row) {
			this.selectedDepartment = Object.assign({}, row);
			this.dialogVisible = true;
			this.isEdit = true;
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		resetForm() {
			this.selectedDepartment = {
				did: '',
				dname: '',
				dpassword: '',
				dmanager: '',
				dphone: '',
				problem: '',
				text: ''
			};
		}
	},
	created() {
		this.fetchDepartments();
	}
};
</script>

<style scoped>
.search-bar {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	margin-bottom: 10px;
}

.add-button {
	margin-bottom: 10px;
}
</style>
